import { APP_ID,APP_KEY,HTTP_REQUEST_URL,TEST_REQUEST_URL } from '../config.js';
import { md5 } from './md5.js';
import os from '../os.js';

/**
 * 发送接口请求
 */
export default function request(url, method, data, opt)
{
  const app = getApp();
  let appId = APP_ID;

  if (url !== "/newWriteLog") {
    url = '/' + appId + url;
  }
  
  let requestUrl = HTTP_REQUEST_URL + url;
  if (app?.globalData?.isTestEnv === true) {
    requestUrl = TEST_REQUEST_URL + url;
  }
  
  let header = {
    'content-type': 'application/json',
    'session': app?.globalData.userInfo?.session || ''
  };
  const showErr = opt.showErr || true;
  Object.assign(data, {
    'app_id': appId,
    'oa_mark': app?.globalData?.launchOptions?.link_id || '',
    'oa_click_id': app?.globalData?.launchOptions?.oa_click_id || '',
    'oa_aid': app?.globalData?.launchOptions?.oa_aid || '',
    'oa_campaign_id': app?.globalData?.launchOptions?.oa_campaign_id || '',
    'oa_cid': app?.globalData?.launchOptions?.oa_cid || '',
    'oa_mid': app?.globalData?.launchOptions?.oa_mid || '',
    'clickid': app?.globalData?.launchOptions?.clickid || '',
    'uid': app?.globalData.userInfo?.uid || 0,
    'device_id': app?.globalData.userInfo?.device_id || '',
    'is_ios': app?.isIPhone() ? 1:0,
    'openid': app?.globalData.userInfo?.openid || '',
    'app_version': app?.globalData.envInfo?.microapp?.mpVersion || '',
    // 'session_key': app?.globalData.userInfo?.session_key || '',
  });
  dealParams(data);
  app?.echo('Request Params: ' + requestUrl, data);
  return new Promise((reslove, reject) => {
    const options = {
      url: requestUrl,
      data: getParams( data || {}),
      header: header,
      method: method || "POST",
      dataType: "json",
      enableCache: false, 
      timeout: 30000, 
    }
    let task = os.request({ 
      ...options,
      success(res) { 
        app.echo('Request Result: ', requestUrl, res.data);
        reslove(res.data, res);
      },
      fail(res) {
        if (showErr) {
          app.Tips({title: `网络错误`, icon: "fail"});
        }
        reject(res);
      },
      complete(res){ 
        // console.log("request: complete", res.data)
      }
    });
  });
}

/**
 * 是否浮点型数字
 */
export function isFloat(value) {
  return typeof value === 'number' && isFinite(value) && !Number.isInteger(value);
}

/**
 * 处理参数 
 */
export function dealParams(params){
  Object.keys(params).forEach(key => {
    if (params[key] === null) {
      params[key] = "";
    }
    if (isFloat(params[key])) {
      params[key] = params[key].toString();
    }
  });
}

/**
 * 参数签名
 */
export function getParams(params){
  const ignoreArr = ['sign', 'app_id', 'channel_id','data'];
  params.timestamp = Date.parse(new Date())/1000;

  // 参数排序
  if(params){
    const sortedKeys = Object.keys(params).sort();
    const sortedObj = {};
    sortedKeys.forEach(key => {
        sortedObj[key] = params[key];
    });
    params = sortedObj;
  }

  // 参数签名加密
  let signStr = '';
  for(let key in params){
      if(ignoreArr.includes(key)){
          continue;
      }
      signStr = signStr + params[key];
  }
  signStr = md5(APP_ID + md5(signStr) + APP_KEY);
  params.sign = signStr;
  return params;
}

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
});

